package hichecker.tools;

import hichecker.university.Course;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.Reader;
import java.io.Writer;

import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Marshaller;
import javax.xml.bind.Unmarshaller;


public class FileManager {
	/**
	 * Writes the object into the file
	 * @param obj
	 * @param filePath
	 */
	public static void saveToXML(File file, Course obj) {
		try {
			JAXBContext context = JAXBContext.newInstance(obj.getClass());
			Marshaller marshaller = context.createMarshaller();
			marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE);
			Writer writer = new FileWriter(file);
			marshaller.marshal(obj, writer);
			writer.close();
		} catch (JAXBException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	public static Object loadFromXML(File file, Class<?> interpretAs) {
		Object course = null;
		try {
			JAXBContext context = JAXBContext.newInstance(interpretAs);
			Unmarshaller unmarshaller = context.createUnmarshaller();
			Reader reader = new FileReader(file);
			course = unmarshaller.unmarshal(reader);
		} catch (JAXBException e) {
			e.printStackTrace();
		} catch (FileNotFoundException e) {
			// TODO warum?
			//e.printStackTrace();
			return null;
		}
		return course;
	}
}
